﻿using Furion.DatabaseAccessor;
using iemtm.WeChat.Core.Extension.Helper;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iemtm.WeChat.Core.Quartz.Job
{
    /// <summary>
    /// 检查微信Token有没有过期
    /// </summary>
     [DisallowConcurrentExecution]//前一次任务未执行完成时不触发下次任务
    public class CheckWeChatAccessTokenJob: IJob
    {
        public  Task Execute(IJobExecutionContext context)
        {
            return Task.Run(() =>
            {
                try
                {
                    //微信-AccessToken
                    var WeiXinConfig = WeChatHelper.WeiXinConfig;
                    if (WeiXinConfig.expiresTime <= DateTime.Now)//如果小于当前时间则表示过期了
                    {
                        var result = WeChatHelper.GetAccessTokenAsync().Result;
                        WeiXinConfig.access_token = result.access_token;
                        WeiXinConfig.expires_in = result.expires_in;
                        WeiXinConfig.getTime = DateTime.Now;
                        WeiXinConfig.expiresTime = DateTime.Now.AddSeconds(WeiXinConfig.expires_in.Value-100);

                        MemoryEntity.gBuffWeiXinConfig.Update(WeiXinConfig);
                        //并同步数据库
                        Db.GetRepository<WeixinConfig>().UpdateInclude(WeiXinConfig, new[] { "access_token", "expires_in", "getTime", "expiresTime" });
                    }

                    if (WeiXinConfig.jsapi_ticket_expiresTime <= DateTime.Now)//如果小于当前时间则表示过期了
                    {
                        var result = WeChatHelper.GetJsApiTicketAsync().Result;
                        WeiXinConfig.jsapi_ticket = result.ticket;
                        WeiXinConfig.jsapi_ticket_expiresTime = DateTime.Now.AddSeconds(result.expires_in - 100);
                        MemoryEntity.gBuffWeiXinConfig.Update(WeiXinConfig);
                        //并同步数据库
                        Db.GetRepository<WeixinConfig>().UpdateInclude(WeiXinConfig, new[] { "jsapi_ticket", "jsapi_ticket_expiresTime" });
                    }
                }catch(Exception ex)
                {
                    
                }

                //微信检 查Jsapi_ticket

            });
        }


    }
}
